package com.danger.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.danger.activity.MainActivity;
import com.danger.activity.R;
import com.danger.model.entity.Song;
import com.danger.util.BitmapUtil;
import com.danger.util.Constant;

import java.util.List;

/**
 * Created by 俊 on 2016/8/16.
 */
public class PlayServiceImpl extends Service implements PlayService {

    private MediaPlayer mediaPlayer;
    private int position;
    private List<Song> songs;
    private Song song;
    private int progress;
    private boolean isPause;

    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();
        new MyThread().start();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent.getAction().equals(Constant.PLAY_MSG)) {
            this.songs = (List<Song>) intent.getSerializableExtra("songs");
            this.position = intent.getIntExtra("position", 0);
            this.song = songs.get(position);
            play();
        } else if (intent.getAction().equals(Constant.PAUSE_MSG)) {
            pause();
        } else if (intent.getAction().equals(Constant.PREVIOUS_MSG)) {
            previous();
        } else if (intent.getAction().equals(Constant.NEXT_MSG)) {
            next();
        } else if (intent.getAction().equals(Constant.DRAG_SEEKBAR)) {
            setProgress(intent);
        } else if (intent.getAction().equals(Constant.NOTIFICATION)) {
            showNotification();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void play() {
        if (song != null) {
            try {
                progress = 0;
                Intent intent = new Intent();
                intent.putExtra("position", position);
                intent.putExtra("type", 1);
                intent.setAction(Constant.UPDATE_UI);
                sendBroadcast(intent);
                mediaPlayer.reset();
                mediaPlayer.setDataSource(song.getUrl());
                mediaPlayer.prepare();
                mediaPlayer.start();
                position = song.getPosition();
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        next();
                    }
                });
            } catch (Exception e) {
                Toast.makeText(this, "播放失败！", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void pause() {
        if (song != null) {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                Intent intent = new Intent();
                intent.setAction(Constant.UPDATE_UI);
                intent.putExtra("type", 2);
                sendBroadcast(intent);
                mediaPlayer.pause();
                isPause = true;
                progress = mediaPlayer.getCurrentPosition();
            } else {
                Intent intent = new Intent();
                intent.setAction(Constant.UPDATE_UI);
                intent.putExtra("type", 3);
                sendBroadcast(intent);
                isPause = false;
                new MyThread().start();
                mediaPlayer.start();
                mediaPlayer.seekTo(progress);
            }
        }
    }

    @Override
    public void previous() {
        if (song != null) {
            if (position == 0) {
                this.song = songs.get(songs.size() - 1);
                position = songs.size() - 1;
            } else {
                this.song = songs.get(position - 1);
                position = position - 1;
            }
            position = song.getPosition();
            Intent intent = new Intent();
            intent.putExtra("position", position);
            intent.putExtra("type", 1);
            intent.setAction(Constant.UPDATE_UI);
            sendBroadcast(intent);
            progress = 0;
            play();
        }
    }

    @Override
    public void next() {
        if (song != null) {
            sendBroadcast(new Intent(Constant.NEXT_MSG));
            if (position == songs.size() - 1) {
                this.song = songs.get(0);
                position = 0;
            } else {
                this.song = songs.get(position + 1);
                position = position + 1;
            }
            position = song.getPosition();
            Intent intent = new Intent();
            intent.putExtra("position", position);
            intent.putExtra("type", 1);
            intent.setAction(Constant.UPDATE_UI);
            sendBroadcast(intent);
            progress = 0;
            play();
        }
    }


    @Override
    public void setProgress(Intent drag_intent) {
        int drag_progress = drag_intent.getIntExtra("progress", 0);
        Log.i("drag", drag_progress + "");
        float temp = (((float) (drag_progress)) / 100) * songs.get(position).getDuration();
        this.progress = (int) temp;
        Log.i("progress", "计算的进度：" + temp);
        if (mediaPlayer != null) {
            if (isPause) {
                mediaPlayer.start();
                Intent intent = new Intent();
                intent.setAction(Constant.UPDATE_UI);
                intent.putExtra("type", 3);
                sendBroadcast(intent);
                isPause = false;
            }
            mediaPlayer.seekTo(this.progress);
            new MyThread().start();
        }
    }

    @Override
    public void stop() {
        if (mediaPlayer.isPlaying() && mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    private class MyThread extends Thread {

        @Override
        public void run() {
            while (true) {
                if (isPause) {
                    break;
                }
                try {
                    sleep(100);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent();
                intent.setAction(Constant.UPDATE_UI);
                intent.putExtra("progress", (long) mediaPlayer.getCurrentPosition());
                intent.putExtra("type", 4);
                intent.putExtra("length", songs.get(position).getDuration());
                sendBroadcast(intent);
            }
        }
    }

    @Override
    public void showNotification() {
        NotificationManager manager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
        RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.notification_layout);
        remoteViews.setTextViewText(R.id.notification_song_name_textView, song.getName());
        remoteViews.setTextViewText(R.id.notification_artist_name_textView, song.getArtist());
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.test);
        int min = bitmap.getHeight() > bitmap.getWidth() ? bitmap.getWidth() : bitmap.getHeight();
        remoteViews.setImageViewBitmap(R.id.notification_artist_photo_imageView, BitmapUtil.createCircleBitmap(bitmap, min));
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContent(remoteViews);
        builder.setContentIntent(pendingIntent);
        builder.setSmallIcon(R.drawable.background);
        Notification notification = builder.build();
        notification.flags = Notification.FLAG_INSISTENT;
        notification.contentView.setOnClickPendingIntent(R.id.notification_layout, pendingIntent);
        manager.notify(0, notification);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stop();
    }
}